import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/models/repair_standard_list_entity.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:kkhousekeep/tools/dialog_util.dart';
import 'package:kkhousekeep/tools/toast_util.dart';

import '../../../../config/constant.dart';
import '../../../../models/order_list_entity.dart';
import '../../../../models/property_order_detail_entity.dart';
import '../../../../models/repair_staff_list_entity.dart';
import '../../../../net/home_order_connect.dart';
import '../../../public/take_picture_screen.dart';
import '../repair/repair_add_controller.dart';

class OrderProcessingReportController extends GetxController {
  late OrderListObj _orderEntity;
  var orderId = 0;
  var fatalType = "".obs;
  var results = "".obs;
  var resultsTextEditController = TextEditingController();
  var reasonAnalysis = "".obs;
  var reasonAnalysisTextEditController = TextEditingController();
  var precaution = "".obs;
  var precautionTextEditController = TextEditingController();
  var evaluation = "".obs;
  var evaluationTextEditController = TextEditingController();
  var costTextEditController = TextEditingController();

  late HomeOrderConnect _homeOrderConnect;

  var staffs = <RepairStaffListObj>[].obs;
  var staffsStringList = <String>[].obs;
  List<RepairStaffListObj> selectedStaff = <RepairStaffListObj>[];
  List<int> selectedStaffIndexs = <int>[];
  var staff = "请选择".obs;

  var standards = <RepairStandardListObj>[].obs;
  var standardsStringList = <String>[].obs;
  RepairStandardListObj? selectedStandard;
  var standard = "请选择".obs;

  var imageDescList = <ImageDescModel>[].obs;
  final ImageDescModel placeholderModel = ImageDescModel(
      isPlaceholder: true,
      absolutePath: 'home_convenient_repair_add_image.png');

  @override
  void onInit() {
    _homeOrderConnect = Get.find<HomeOrderConnect>();
    _orderEntity = Get.arguments;
    orderId = _orderEntity.id;
    super.onInit();
    imageDescList.add(placeholderModel);
    _loadNetworkData();
    resultsTextEditController.addListener(() {
      results.value = resultsTextEditController.text;
    });
    reasonAnalysisTextEditController.addListener(() {
      reasonAnalysis.value = reasonAnalysisTextEditController.text;
    });
    precautionTextEditController.addListener(() {
      precaution.value = precautionTextEditController.text;
    });
    evaluationTextEditController.addListener(() {
      evaluation.value = evaluationTextEditController.text;
    });
  }

  Future<void> _loadNetworkData() async {
    PropertyOrderDetailEntity orderDetailEntity =
        await _homeOrderConnect.getOrderDetail(orderId: orderId);
    PropertyOrderDetailObj orderDetailObj = orderDetailEntity.obj;
    fatalType.value = orderDetailObj.fatalType;
  }

  Future<void> getStaffList() async {
    RepairStaffListEntity repairStaffListEntity =
        await _homeOrderConnect.getRepairStaffList();
    staffs.value = repairStaffListEntity.obj;
    staffsStringList.value = staffs.map((e) => e.name).toList();
  }

  Future<void> getStandardList() async {
    RepairStandardListEntity repairStandardListEntity = await _homeOrderConnect
        .getOrderRepairStandardList(workOrderId: orderId);
    standards.value = repairStandardListEntity.obj;
    standardsStringList.value = standards.map((e) => e.name).toList();
  }

  selectStaff(List<int> indexs) {
    selectedStaffIndexs = indexs;
    selectedStaff.clear();
    for (var value in indexs) {
      selectedStaff.add(staffs[value]);
    }
    String staff = "";
    if (selectedStaff.isNotEmpty) {
      for (var element in selectedStaff) {
        if (staff.isNotEmpty) {
          staff += ";";
        }
        staff += element.name;
      }
    }
    this.staff.value = staff;
  }

  selectStandard(RepairStandardListObj standardListObj) {
    if (selectedStandard == null ||
        standardListObj.id != selectedStandard?.id) {
      selectedStandard = standardListObj;
      standard.value = standardListObj.name;
    }
  }

  void performClickImageItem(ImageDescModel model) {
    FocusManager.instance.primaryFocus?.unfocus();
    if (model.isPlaceholder) {
      ///点击占位图
      Get.to(() => TakePictureScreen(
            photoPathCallBack: <PickPictureModel>(model) {
              if (imageDescList.length > 2) {
                imageDescList.remove(placeholderModel);
              }
              imageDescList.add(ImageDescModel(
                networkPath: model.netPath,
                absolutePath: model.cachePath,
              ));
            },
          ));
      return;
    }

    ///展示图片
    Get.to(() => DisplayPictureScreen(
          imagePath: model.absolutePath,
          isShowRetake: false,
        ));
  }

  void performClickDeleteImage(ImageDescModel model) {
    imageDescList.remove(model);
    bool hasPlaceholder = imageDescList.any((element) => element.isPlaceholder);
    if (!hasPlaceholder) {
      imageDescList.insert(0, placeholderModel);
    }
  }

  void summit() {
    if (selectedStandard == null) {
      ToastUtils.showToast(tip: "请选择维修标准");
      return;
    }
    if (results.value.isEmpty) {
      ToastUtils.showToast(tip: "请填写处理结果");
      return;
    }
    List<String> pics = [];
    for (var element in imageDescList) {
      if (!element.isPlaceholder && element.networkPath.isNotEmpty) {
        pics.add(element.networkPath);
      }
    }

    if (pics.isEmpty) {
      ToastUtils.showToast(tip: "请上传维修照片");
      return;
    }

    if (costTextEditController.text != "" &&
        !costTextEditController.text.isNum) {
      ToastUtils.showToast(tip: "请正确填写金额");
      return;
    }

    orderComplete(pics);
  }

  orderComplete(List<String> pics) async {
    String staff = "";
    if (selectedStaff.isNotEmpty) {
      for (var element in selectedStaff) {
        if (staff.isNotEmpty) {
          staff += ",";
        }
        staff += element.id.toString();
      }
    }
    var response = await _homeOrderConnect.orderComplete(
        orderId: orderId,
        standardId: selectedStandard!.id,
        result: results.value,
        cause: reasonAnalysis.value,
        propose: precaution.value,
        appraise: evaluation.value,
        cost: costTextEditController.text == ""
            ? 0
            : double.parse(costTextEditController.text),
        repairStaffId: staff,
        pics: pics);
    if (response == null) {
      return;
    }
    if (response.code == ResponseCode.success) {
      Get.back(result: Constant.resultOK);
    } else {
      DialogUtil.showNetworkFail();
    }
  }
}
